<?php
require_once 'services/TIntrinsicPageService.inc';
require_once 'models/acl.inc';
require_once 'core/utils/repository.inc';

class TAdminService extends TIntrinsicPageService implements IItemNavigation {
	private $_class_map_;
	private $_map_initiated_ = false;
	
	private $_prev_uri_;
	private $_default_pages_;
	
	private $_conf_front_place_ = null;
	
	private $_target_app_private_dir_ = null;
	
	private $_target_app_dir_ = null;

/**
 * @var IKeyValueRepository
 */	
	protected $_ioc_shop_settings_;
	
/**
 * @var IKeyValueRepository
 */
	protected $_ioc_meta_settings_;
	
	public function __get($nm){
		switch ($nm){
			case 'TargetAppPrivateDir':{
				if (!$this->_target_app_private_dir_)
					$this->_target_app_private_dir_ = $this->Application()->AdjustPath('../private');
				return $this->_target_app_private_dir_;
			}break;
			case 'TargetAppDir':{
				if (!$this->_target_app_dir_)
					$this->_target_app_dir_ = $this->Application()->AdjustPath('..');
				return $this->_target_app_dir_;
			}break;
			default:return parent::__get($nm);break;
		}
	}
	
	public function __set($nm,$value){
		switch ($nm){
			case 'TargetAppPrivateDir':$this->_target_app_private_dir_ = $this->Application()->AdjustPath($value);break;
			case 'TargetAppDir':$this->_target_app_dir_ = $this->Application()->AdjustPath($value);break;
			case 'DefaultPages':{
				if (is_string($value)){
					$temp = TConvertions::ConvertToArray($value,array(',','='),array(false,true));
					$value = array();
					foreach ($temp as $key=>$page){
						if (!is_numeric($key))
							if (defined('TMSRole::'.$key))
								$key = constant('TMSRole::'.$key);
						$value[$key] = $page;		 
					}
				}	
				if (is_array($value))
					$this->_default_pages_ = $value;	
			}break;
			case 'ClassMap':{
				$this->_init_map();
				if (is_string($value))
					$value = TConvertions::ConvertToArray($value,array(',','='),array(false,true));
				if (is_array($value)){
					if (!is_array($this->_class_map_))
						$this->_class_map_ = array();
					$this->_class_map_ = $value + $this->_class_map_;
				}	
			}break;
			default:parent::__set($nm,$value);break;
		}
	}
	
	private function _init_map(){
		if (!$this->_map_initiated_){
			$this->_map_initiated_ = true;
			$fn = $this->Application()->PrivateDir().'/classmap.conf';
			if (file_exists($fn))
				$this->ClassMap = file_get_contents($fn);
			$fn = $this->Application()->OverrideDir().'/classmap.conf';
			if (file_exists($fn))
				$this->ClassMap = file_get_contents($fn);
		}
	}
	
/**
 * @see TPageService::getDefaultPage()
 * @return TIntrinsicPage
 */	
	protected function getDefaultPage(){
		$u = $this->Acl->CurrentUser();
		if ($u instanceof TMSUser){
			if ($u->Roles & TMSRole::ADMIN){
				if (isset($this->_default_pages_[TMSRole::ADMIN]))
					return $this->getPage($this->_default_pages_[TMSRole::ADMIN]);
			}
			 
			foreach ($this->_default_pages_ as $code => $page)
				if ($u->Roles & $code)
					return $this->getPage($page);
		}
		return parent::getDefaultPage();
	}

	private function _prefix_path($path,$class,&$params){
		$this->_init_map();
		if (isset($this->_class_map_[$class]))
			return $this->_class_map_[$class].($path?('/'.$path):'');

		if (is_subclass_of($class, 'TMSNomenclature'))
			return $this->_prefix_path($path, 'TMSNomenclature', $params);
		
		if (is_subclass_of($class, 'TMSArticle'))
			return $this->_prefix_path($path, 'TMSArticle', $params);

		if (is_subclass_of($class, 'TMSProductPage'))
			return $this->_prefix_path($path, 'TMSProductPage', $params);
		
		if (is_subclass_of($class, 'TMSClient'))
			return $this->_prefix_path($path, 'TMSClient', $params);		
		
		if (is_subclass_of($class, 'TNOrmObject')){
			$params['class'] = $class;
			return 'glossary'.($path?('/'.$path):'');
		}
		
		return null;
	}
	
	public function GlossaryUrl($classname,$section = null){
		return $this->Url('glossary'.($section?'/'.$section:''),null,null,array("class"=>$classname));
	}
	
	public function ListUrl($classname){
		$params = array();
		if ($path = $this->_prefix_path('', $classname,$params)){
			if ($pn = $this->request->Cookie($path.'_pn')){
				$params['pagenum'] = $pn;
			}
			if ($node = $this->request->Cookie($path.'_node')){
				$params['node'] = $node;
			}
			
			return $this->Url($path,null,null,$params);
		} return null;
	}
	
	public function CollectionPath($path,$container){
		$result = array();
		$path = dirname($path);
		while ($path){
			$page = $this->getPage($path);
			$pageitem = $page->Model->GetItem($container);
			$result[$this->Url($path.'/item',null,null,array('id'=>$container))] = (string)$pageitem;
			if ($page instanceof TMSCollectionPage){
				$container = $pageitem->Property($page->FilterProperty)->ReferedInstance();
				if ($container)
					$container = $container->ItemId();
				$result[$page->Url(null,null,array('container'=>$container))] = $page->Title();	
			} else {
				$result[$page->Url()] = $page->Title();
				break;
			}
			$path = dirname($path);
		}
		return array_reverse($result,true);
	}
	
	public function ListPage($classname){
		$params = array();
		if ($path = $this->_prefix_path('', $classname,$params))
			return $this->getPage($path);
		return null;
	}
	
	public function ItemPage(IItem $item){
		if ($path = $this->_prefix_path('item', $item->ClassName()))
			return $this->getPage($path);
		return null;
	}
	
	public function ItemCreateUrl($classname, array $params = array()){
		if ($path = $this->_prefix_path('create', $classname, $params))
			return $this->Url($path,null,null,$params);
		return null;	
	}
	
	public function ItemEditUrl(IItem $item, array $parameters = array()){
		return $this->ItemNavigationUrl($item, null,null,$parameters);
	}
	
	public function ItemNavigationUrl(IItem $item, $controller = null, $method = null, array $parameters = array()){
		if ($item){
			if ($item instanceof TCandyItem){
				if ($item->Base instanceof TMSArticle)
					return $this->ItemNavigationUrl($item->Nomenclature,$controller,$method,$parameters);
				/*if ($item->Base instanceof TMSOrderPosition){
					if (isset($parameters['container'])) unset($parameters['container']);
					return $this->ItemNavigationUrl($item->Product,$controller,$method,$parameters);
				}*/
			}
			if ($path = $this->_prefix_path('item', $item->ClassName(),$parameters))
				return $this->Url($path,$controller,$method,array('id'=>$item->ItemId()) + $parameters);
		}
		return null;
	}
	
	public function FrontUrl($service = null,array $parameters = array()){
		if ($this->FrontPlace)
			return $this->Application()->Url($service,$parameters,$this->FrontPlace);
		return $this->Application()->Url($service,$parameters,'..');
	}
	
	protected function handleRequest(TRequest $request){	
		if (!($this->Acl->CurrentUser() instanceof TMSUser)){
			$request->src = $this->Application()->Uri();
			$request->path = 'login'; 
		}
		return parent::handleRequest($request);
	}
}